package gamecfg

import (
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/glog"
	"sort"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/xrjson"
)

const (
	NonTaskReset  = 0
	DayTaskReSet  = 1
	WeekTaskReset = 2
)

var taskMap = make(map[uint64]*TaskCfg)
var TaskTypeMap = make(map[uint8][]*TaskCfg)
var TaskArray = make([]*TaskCfg, common.Zero)

type TaskCfg struct {
	Id          uint64 `json:"id"`
	TaskType    uint8  `json:"taskType"`
	Finish      string `json:"finish"`
	Order       int    `json:"order"`
	Reward      string `json:"reward"`
	TimeHandler int    `json:"timeHandler"`
}

func initTask() {
	xrjson.RegLoadJsonHandler("task.json", load)
}

type ByTaskOrder []*TaskCfg

func (a ByTaskOrder) Len() int {
	return len(a)
}
func (a ByTaskOrder) Less(i, j int) bool {
	return a[i].Order < a[j].Order
}
func (a ByTaskOrder) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

func load(jsonData string) {
	err := json.Unmarshal([]byte(jsonData), &taskMap)
	if err != nil {
		panic(fmt.Errorf("%v 文件加载错误 %v", jsonData, err))
	}
	for _, val := range taskMap {
		TaskArray = append(TaskArray, val)
		typeLst, ok := TaskTypeMap[val.TaskType]
		if !ok {
			TaskTypeMap[val.TaskType] = []*TaskCfg{val}
		} else {
			TaskTypeMap[val.TaskType] = append(typeLst, val)
		}
	}
	sort.Sort(ByTaskOrder(TaskArray))
	glog.Warningf(gctx.New(), "%s数据加载成功,长度:%v", jsonData, len(taskMap))
}

func GetTaskById(taskCfgId uint64) *TaskCfg {
	val, ok := taskMap[taskCfgId]
	if !ok {
		return nil
	}
	return val
}

func (this *TaskCfg) GetFinish() []uint64 {
	var ret []uint64
	json.Unmarshal([]byte(this.Finish), &ret)
	return ret
}

func (this *TaskCfg) GetReward() [][]uint64 {
	var ret [][]uint64
	json.Unmarshal([]byte(this.Reward), &ret)
	return ret
}
